import sys,config,webbrowser,wifiauthtool
from functools import partial
from PyQt5.QtWidgets import  QSystemTrayIcon, QMenu, QAction,QMessageBox
from PyQt5.QtGui import QIcon
class TrayIconApp(QSystemTrayIcon):
    def __init__(self, icon:QIcon,parent=None):
        super().__init__(icon, parent)
        
        self.initUI()
    def webopen(self,url:str):
        
        if "webvpn.stu.edu.cn" in url:

            if hasattr(self.mainwin,"window1"):
                self.mainwin.window1.detect_vpnlogin()
            try:
                twfid = config.gcon("setting","twfid")
            except Exception:
                QMessageBox.about(self,"提示：","twfid未获取成功，请尝试点击进入http无限流")
                print("twfid未存在")
                return
            
            webbrowser.open(f"https://webvpn.stu.edu.cn/portal/shortcut.html?twfid={twfid}&url={url}")
                
        else:
            webbrowser.open(url)
    def reset_login(self,conf):
        now_conf = config.get_conf()
        now_toml = config.gtoml()
        now_twfid = now_toml['setting']['twfid']
        config.set_conf(conf)
        toml = config.gtoml()
        if wifiauthtool.wifi_auth(toml['setting']['name'],toml['setting']['password']):
            config.wcon("setting","twfid",now_twfid)#保留原来的twfid
            QMessageBox.about(self.mainwin,"提示：","已切换账号并重新登录,账号信息可能需要一分钟后刷新")
        else:
            config.set_conf(now_conf)
            QMessageBox.about(self.mainwin,"提示：","切换账号失败，请检查账号信息")
    def initUI(self):
        menu = QMenu("头大WiFi认证")

        try:
            toml = config.gtoml()
            ##自定义菜单
            div_menu = toml["menu"]["enable"].split('|')
            for d in div_menu:
                url = toml[d]["link"]
                name = toml[d]["name"]
                try:
                    icon = toml[d]["icon"]
                except:
                    icon = ""


                if icon != "":
                    action = QAction(QIcon(icon),name, self)
                else:
                    action = QAction(name, self)
                
                
                action.triggered.connect(partial(self.webopen,url))
                menu.addAction(action)
            ##切换登录账号

            conf_list = config.get_valid_conf_list()
            for conf in conf_list:
                action = QAction(f"切换{conf}中的账号", self)
                action.triggered.connect(partial(self.reset_login,conf))
                menu.addAction(action)

        except Exception as e:
            print(f"创建自定义菜单出现错误: {e}")
 
        about_action = QAction("关于", self)
        about_action.triggered.connect(self.about)
        menu.addAction(about_action)

        exit_action = QAction("退出", self)
        exit_action.triggered.connect(self.exitApp)
        menu.addAction(exit_action)
        
        self.setContextMenu(menu)
        
        self.activated.connect(self.on_activated)
        self.show()
    def on_activated(self, reason):
        if reason == QSystemTrayIcon.Trigger:
            if hasattr(self,"win"):
                self.win.keyhandle()
    def about(self):
        name = "头大WiFi认证"
        author = "Tiosa"
        QQ = "2546168529"
        ver = "2.5.3"
        date = "2025-4-21"
        git = "https://gitee.com/tiosa/touda_wifi_v2"
        QMessageBox.about(self.mainwin, "关于",f"{name}\n作者：{author}\nQQ：{QQ}\n版本：{ver}\n最后更新日期：{date}\n源代码仓库：{git}")
    def exitApp(self):
        sys.exit()
